//
//  WHNetwrokTool.swift
//  microblog
//
//  Created by Apple on 15/11/26.
//  Copyright © 2015年 Apple. All rights reserved.
//

import UIKit
import AFNetworking

class WHNetwrokTool: AFHTTPSessionManager {

    //单例
    static let sharedInstance: WHNetwrokTool = {
        //url 
        let baseurl = NSURL(string: "https://api.weibo.com/")
        let tool = WHNetwrokTool(baseURL: baseurl)
        // 添加响应的序列化器
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()

    //Oaith
    private let client_id = "739480267"
    /// 申请应用时分配的AppSecret
    private let client_secret = "8796a8cd3ddf97cfc1a38c4d808bff17"
    /// 授权回调地址, 一定要一模一样
    let redirect_uri = "http://www.baidu.com/"
    //返回授权界面的URL地址
    func oauthUrl() ->NSURL {
        //get 拼接登录界面的请求地址
        let urlstring = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        //返回去，创建对象
        return NSURL(string: urlstring)!
    }
    
    // 加载AccessToken 只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code: String, finished:(result:[String:AnyObject]?,error:NSError?) ->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数(5个)
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,//需要别人传入
            "redirect_uri": redirect_uri
        ]
         //发送post请求
        POST(urlString, parameters: parameters, success: { (_,result) -> Void in
            //返回结果
            print("result1:\(result) ")
            finished(result: result as? [String : AnyObject], error: nil)
            }) { (_, error) -> Void in
            //返回错误
            print("error:\(error) ")
            finished(result:nil,error:error)
        }
    }
}
